package net.chathu.airgw
{
	import flash.desktop.NativeApplication;
	import flash.display.IDrawCommand;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLStream;
	import madebypi.utils.Properties;
	import madebypi.utils.PropertiesParser;
	
	/**
	 * ...
	 * @author ze
	 */
	public class Config
	{
		//TODO: backup keszites a config fajlrol
		
		//CONSTANTS:
		public static const DEBUG:Boolean = true;
		public static const PROGRAM_NAME:String = "AirGW";
		public static const IRC_NETWORK_NAME:String = "AirGW"; //shouldn't contain spaces!
		public static const IRC_HOST:String = "fake.gw.chat.hu";
		public static const IRC_USER_HOST:String = ".chat.hu";
		public static const GW_ECHO_NICK:String = "Gateway";
		public static const GW_WHOIS_LOCATION:String = "with a direct connection to ARPANET military network.";
		public static const CHATSERV_NICK:String = "Chat.hu";
		
		public static const IRC_CHAR_BOLD:String = "\u0002"; //""
		public static const IRC_CHAR_UNDERLINED:String = "\u001F"; //""
		public static const IRC_CHAR_REVERSED:String = "\u0016"; //""
		public static const IRC_CHAR_COLOR:String = "\u0003"; // ""
		
		public static const CREATED_DATE:Date = new Date();
		public static const EXTRA_WELCOME_MESSAGE:String = IRC_CHAR_COLOR + "9" + "Üdvözöl az " + PROGRAM_NAME + "!" + IRC_CHAR_COLOR;
		public static const MOTD:String = "Hibákat, fejlesztési javaslatokat itt rögzíthetitek:\n" + IRC_CHAR_COLOR + "9http://code.google.com/p/airgateway/issues/list\nElérhető parancsok listája:\n" + IRC_CHAR_COLOR + "0,4 /gwhelp " + IRC_CHAR_COLOR+"\nKonfigurációs fájl példa megtalálható a telepítés könyvtárában!";
		public static const REDIRECTOR_VERSION_INFO:String = "version 0 64 beta";
		
		// --- other inner variables --
		
		private static var properties:Properties = new Properties();
		//public static var PROGRAM_VERSION:String = "";
		private static var _program_version:String;
		private static var _debug_build:Boolean = false;
		
		public static function get PROGRAM_VERSION():String
		{
			if (!_program_version)
			{
				//VERSION INIT:
				var descriptor:XML = NativeApplication.nativeApplication.applicationDescriptor;
				var ns:Namespace = descriptor.namespace();
				var version:String = descriptor.ns::versionLabel;
				var versionNumber:String = descriptor.ns::versionNumber;
				var id:String = descriptor.ns::id;
				trace("Version: " + version);
				trace("VersionNumber: " + versionNumber);
				if (id.indexOf("DEBUG") >= 0)
				{
					_debug_build = true;
				}
				_program_version = versionNumber;
			}
			return _program_version;
		}
		
		public static function get IS_DEBUG_BUILD():Boolean
		{
			if (!_program_version)
			{
				PROGRAM_VERSION;
			}
			return _debug_build;
		}
		
		
		//Real config keys:
		public static var CHAT_CLIENT_VERSION:String;
		public static var CHAT_SERVER_HOST:String;
		public static var CHAT_SERVER_PORTS:Array;
		
		/*public static function get LISTENING_PORT():int
		{
			return IS_DEBUG_BUILD ? _listening_port_debug : _listening_port_normal;
		}*/
		
		public static var LISTENING_PORT:int;
		
		
		public static var IRC_ENCODING:String;
		//& karakterrel kell kezdodnie:
		public static var P2P_AUTOJOIN_CHANNEL:String;		
		public static var USERSLIST_CHANNEL:String;
		public static var INCLUDE_AGE_AND_GENDER_IN_HOST:Boolean;
		public static var INCLUDE_AGE_AND_GENDER_IN_NAME:Boolean;
		public static var HIDE_APPLICATION_ON_CLOSE_CLICK:Boolean;
		
		
		
		
		
		public function Config()
		{
		
		}
		
		public static function reload():void
		{
			//var prefsFile:File = File.applicationDirectory;
			//Debug.echo("Application storage dir: " + prefsFile.toString());
			//var cfgFile:File = prefsFile.resolvePath("config.cfg");
			Debug.echo("Config file path: " + configFile.nativePath);
			
			if (configFile.exists)
			{
				var fileStream:FileStream = new FileStream();
				var opened:Boolean = false;				
				try {
					fileStream.open(configFile, FileMode.READ);
					opened = true;
				} catch (error:Error) {
					Debug.echo("Can't read config file.");
				}
				
				if(opened) {
					var content:String = "";
					while (fileStream.bytesAvailable>0)
					{
							
						var chunk:String = fileStream.readMultiByte(fileStream.bytesAvailable, File.systemCharset);
						content += chunk;
					}
					properties = PropertiesParser.parse(content);
					
				} else {
					Debug.echo("Couldn't open configuration file!");	
				}
				fileStream.close();
			} else {
				Debug.echo("Config file not found!");
			}
			
			setupProperties();
		}
		
		
		private static function setupProperties():void {
			var tempStr:String;
			var tempBool:*;
			var tempInt:int;
			
			//client version
			CHAT_CLIENT_VERSION = properties.getProperty("chatClientVersion") || "v20111111";
			//chat server host
			CHAT_SERVER_HOST = properties.getProperty("chatServerHost") || "217.65.97.41";
			//chat server port list
			var portArrayStr:String = properties.getProperty("chatServerPorts");
			var portArray:Array;
			if (portArrayStr)
			{
				portArray = portArrayStr.split(",");
			}
			var portError:Boolean = false;
			
			for (var i:String in portArray) {
				if (!isValidPort(portArray[i]))
				{
					portError = true;
				}
			}
			
			if (portError) {
				Debug.echo("Hibás chat szerver portlista: " + portArrayStr);
			}
	
			CHAT_SERVER_PORTS = (portArray && portArray.length > 0 && ! portError) ? portArray : [23, 53, 77, 110, 443, 4000];
			
			//listening port
			
			//normal listening port:
			tempStr = properties.getProperty("listeningPort");
			tempInt = parseInt(tempStr);
			LISTENING_PORT = isValidPort(tempInt) ? tempInt : 6667;
			
			/*
			//debug listening port:
			tempStr = properties.getProperty("listeningPortDebug");
			tempInt = parseInt(tempStr);
			_listening_port_debug = isValidPort(tempInt) ? tempInt : 6777;
			*/
			
			//encoding
			IRC_ENCODING = properties.getProperty("ircEncoding") || "UTF-8";
			//autojoin channel
			tempStr = properties.getProperty("p2pAutoJoinChannel");
			P2P_AUTOJOIN_CHANNEL = (tempStr && tempStr.indexOf("&")==0 && tempStr.length>2) ? tempStr : "&gw";		
			//userlist channel
			tempStr = properties.getProperty("userListChannel");
			USERSLIST_CHANNEL = (tempStr && tempStr.indexOf("&")==0 && tempStr.length>2) ? tempStr : "&users";
			//booleans:
			//age and gender in host
			tempBool = parseBoolean(properties.getProperty("includeAgeAndGenderInHost"));
			INCLUDE_AGE_AND_GENDER_IN_HOST = (tempBool != null) ? tempBool : true;
			//age and gender in name
			tempBool = parseBoolean(properties.getProperty("includeAgeAndGenderInName"));
			INCLUDE_AGE_AND_GENDER_IN_NAME = (tempBool != null) ? tempBool : false;
			
			//hide app on close click?
			tempBool = parseBoolean(properties.getProperty("hideApplicationOnCloseClick"));
			HIDE_APPLICATION_ON_CLOSE_CLICK = (tempBool != null) ? tempBool : true;
			
		}
		
		private static function isValidPort(port:*):Boolean {
			if (port is String) {
				port = parseInt(port);
			}
			
			if (port is Number){
				if (isNaN(port) || port <= 0 || port >= 65536) {
					return false;
				} else {
					return true;
				}
			} else {
				return false;
			}
		}
		
		private static function parseBoolean(str:String):* {
			if (str == null) {
				return null;
			} else if (str.toLowerCase() == "true") {
				return true;
			} else if (str.toLowerCase() == "false" ) {
				return false;
			} else {
				return null;
			}
		}
		
		private static function get configFile():File
		{
			
			var appDir:File = File.applicationDirectory;
			var cfgFile:File;
			if (IS_DEBUG_BUILD) {
				var appDirByNativePath:File = new File(appDir.nativePath);
				var appParentDir:File =  appDirByNativePath.parent;
				cfgFile = appParentDir.resolvePath("debug/config.cfg");				
			} else {
				cfgFile = appDir.resolvePath("config.cfg");
			}
			
			
			return cfgFile;
		}
		
		public static function save():void
		{
			
			Debug.echo("Application config file: " + configFile.nativePath);
			var opened:Boolean = false;
			var fileStream:FileStream = new FileStream();
			

			try {
				fileStream.open(configFile, FileMode.WRITE);
				opened = true;
			} catch (error:Error) {
				//Debug.echo(error.message);
			}
			/*
			if (!opened) {
				try {
					Debug.echo("Can't open " + configFile.nativePath + ". Open secondary location..");	
					var appDir:File = File.applicationDirectory;
					var appDirByNativePath:File = new File(appDir.nativePath);//appDir.parent;
					var appParentDir:File =  appDirByNativePath.parent;
					var file:File = appParentDir.resolvePath("deploy/config.cfg");
					fileStream.open(file, FileMode.WRITE);
					
					opened = true;
				} catch (error:Error) {
					Debug.echo("Can't open secondary file: " + file.nativePath);	
					Debug.echo(error.message);
				}
			}*/
			
			if(opened) {
				fileStream.writeMultiByte("-not yet implemented-", File.systemCharset);
				fileStream.close();
			} else {
				Debug.echo("Couldn't save configuration file!");	
			}
		}
	
	}

}
